<?php

namespace siafei\Reporting;


class ReportManager
{
    protected $app;

    protected $driver = [];

    public function __construct($app)
    {
        $this->app = $app;
        $this->initDriver();
    }


    /**
     * 上报消息
     * @param $message
     * @param null $driver 上报类型 dingtalk 钉钉  email 邮件 mobile 短信
     */
    public function report($message, $driver = null)
    {
        if (empty($driver)) {
            $this->initDriver();
        }
        if ($driver && !empty($this->driver[$driver])) {
            ($this->driver[$driver])->report($message);
        } else {
            foreach ($this->driver as $driver) {
                $driver->report($message);
            }
        }
    }

    /**
     * 初始化上报类型
     * @param null $driver
     */
    protected function initDriver()
    {
        $config = $this->getConfig();
        foreach ($config['report'] as $report) {
            $this->driver[$report] = $this->resolve($report);
        }
        //如果没设置上报类型则使用默认类型
        if (empty($this->driver)) {
            $this->driver[$config['default']] = $this->resolve($config['default']);
        }
    }


    /**
     * 创建上报类型
     * @param null $name
     * @return mixed
     * @throws \Exception
     */
    protected function resolve($name = null)
    {
        //dingtalk 钉钉  email 邮件 mobile 短信
        $config = $this->getConfig();
        switch ($name) {
            case 'dingtalk':
                $driver = $this->resolveDingtalk($config['dingtalk']);
                break;
            case 'email':
                $driver = $this->resolveEmail($config['email']);
                break;
            case 'mobile':
                $driver = $this->resolveMobile($config['mobile']);
                break;
            default:
                throw new \Exception("不存在的上报类型");
        }
        return $driver;
    }


    /**
     * 创建钉钉上报类型
     * @param $config
     * @return DingTalkReporting
     */
    protected function resolveDingtalk($config)
    {
        return new DingTalkReporting($config);
    }

    /**
     * 创建邮件上报类型
     * @param $config
     */
    protected function resolveEmail($config)
    {
        return new EmailReporting($config);
    }

    /**
     * 创建短信上报类型
     * @param $config
     */
    protected function resolveMobile($config)
    {
        //todo
        return new MobileReporting($config);
    }

    /**
     * 获取配置
     * @return mixed
     */
    protected
    function getConfig()
    {
        return $this->app['config']['report'];
    }

}